<!-- 购物卡结佣管理-购物卡结佣--->
<template>
  <div class="commission">
    <el-breadcrumb separator="/" class="bread-title">
      <el-breadcrumb-item :to="{ path: '/shoppingCardSettlement' }">购物卡结佣</el-breadcrumb-item>
      <el-breadcrumb-item>结佣</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="order">
      <span>
        <b>结算单id:</b>
        {{brokerApply.batchCode}}
      </span>
    </div>
    <commissions :brokerApply="brokerApply" :awardInfoList="awardInfoList"></commissions>
    <div class="textTitle">
      <span>
        购物卡结佣：
        <small>（说明：按照订单序号的顺序逐一匹配金额，勾选购物卡。）</small>
      </span>
    </div>
    <div class="textSub">
      <span>
        <b>金额合计：</b>
        {{totalAmounts()}}
      </span>
      <span>
        <b>数量：</b>
        {{multipleSelectionAll.length}}
      </span>
    </div>
    <el-table
      ref="multipleTable"
      :data="cartLists"
      @selection-change="handleSelectionChange"
      border
      style="width: 100%"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column align="center" prop="id" label="购物卡id" width="80"></el-table-column>
      <el-table-column align="center" prop="devName" label="所属楼盘"></el-table-column>
      <el-table-column align="center" prop="typeName" label="购物卡类别"></el-table-column>
      <el-table-column align="center" prop="cardCode" label="卡号"></el-table-column>
      <el-table-column align="center" prop="cardPassword" label="卡密"></el-table-column>
      <el-table-column align="center" :formatter="cardDenomination" sortable  label="面额"></el-table-column>
      <el-table-column align="center" prop="cardMedia" label="电子卡/实体卡">
        <template slot-scope="scope">
          <span v-if="scope.row.cardMedia == 1">电子卡</span>
          <span v-else>实体卡</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="inStoreDate" label="入库时间"></el-table-column>
    </el-table>
    <div class="pagebar">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next"
        :current-page.sync="tableConfig.pageNum"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="tableConfig.pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :total="cartTotal"
      ></el-pagination>
    </div>
    <div class="forms" v-if="isChange">
      <el-button type="primary" @click="determine">确定</el-button>
      <el-button @click="goBack">返回</el-button>
    </div>
    <div class="forms" v-else>
      <el-button type="primary" @click="confirm">确认结佣</el-button>
      <el-button @click="onClear">取消</el-button>
    </div>
  </div>
</template>
<script>
import api from "@/api/apiPath";
import commissions from "../../common/xkCommission";
import utils from "@/common/utils";
export default {
  name: "commission",
  components: {
    commissions
  },
  data() {
    return {
      cartTotal: 0,
      tableConfig: {
        pageSize: 10,
        pageNum: 1,
        devId: "",
        terminalSource: '',
        orderIdList: []
      },
      cardIds: [], // 更改跳转过来的 购物卡集合id
      brokerApply: {}, // 经纪人信息
      awardInfoList: [], // 订单明细
      totalAmount: 0, // 订单金额合计
      cardAmount: 0, // 购物卡金额合计
      batchCode: "", // 批次号
      sourceCategory: '',
      isChange: false,
      cartLists: [], // 购物卡列表
      multipleSelectionAll: [], // 所有选中的数据包含跨页数据
      multipleSelection: [], // 当前页选中的数据
      idKey: "id" // 标识列表数据中每一行的唯一键的名称(需要按自己的数据改一下)
    };
  },
  created() {
    this.batchCode = this.$route.query.batchCode;
    this.sourceCategory = this.$route.query.sourceCategory;
    // 用于判断是否是来自更改
    if (this.$route.query.isChange) {
      this.isChange = true;
    }
    this.brokerApply.isRecord = false;
    this.cardIds = this.$route.query.cardIds;
    this.tableConfig.orderIdList = this.$route.query.orderIdList
    this.tableConfig.terminalSource = this.sourceCategory
    this.brokerInfo();
  },
  methods: {
    // 金额合计
    totalAmounts() {
      let nums = 0;
      nums = this.multipleSelectionAll.reduce((p, e) => p + e.cardDenomination, 0);
      this.cardAmount = nums;
      utils.formatMoney(nums);
      return `￥${nums}元`;
    },
    cardDenomination(row) {
      return utils.formatMoney(row.cardDenomination)
    },
    // 设置选中的方法
    setSelectRow() {
      if (!this.multipleSelectionAll || this.multipleSelectionAll.length <= 0) {
        return;
      }
      // 标识当前行的唯一键的名称
      let idKey = this.idKey;
      let selectAllIds = [];
      let that = this;
      this.multipleSelectionAll.forEach(row => {
        selectAllIds.push(row[idKey]);
      });
      this.$refs.multipleTable.clearSelection();
      for (var i = 0; i < this.cartLists.length; i++) {
        if (selectAllIds.indexOf(this.cartLists[i][idKey]) >= 0) {
          // 设置选中，记住table组件需要使用ref="multipleTable"
          this.$refs.multipleTable.toggleRowSelection(this.cartLists[i], true);
        }
      }
    },
    // 记忆选择核心方法
    changePageCoreRecordData() {
      // 标识当前行的唯一键的名称
      let idKey = this.idKey;
      let that = this;
      // 如果总记忆中还没有选择的数据，那么就直接取当前页选中的数据，不需要后面一系列计算
      if (this.multipleSelectionAll.length <= 0) {
        this.multipleSelectionAll = this.multipleSelection;
        console.log(this.multipleSelectionAll)
        return;
      }
      console.log(this.multipleSelectionAll)
      // 总选择里面的key集合
      let selectAllIds = [];
      this.multipleSelectionAll.forEach(row => {
        selectAllIds.push(row[idKey]);
      });
      console.log('总选择的key', selectAllIds)
      let selectIds = [];
      // 获取当前页选中的id
      this.multipleSelection.forEach(row => {
        selectIds.push(row[idKey]);
        // 如果总选择里面不包含当前页选中的数据，那么就加入到总选择集合里
        if (selectAllIds.indexOf(row[idKey]) < 0) {
          that.multipleSelectionAll.push(row);
        }
      });
      console.log('当前也的选中id',selectIds)
      let noSelectIds = [];
      // 得到当前页没有选中的id
      this.cartLists.forEach(row => {
        if (selectIds.indexOf(row[idKey]) < 0) {
          noSelectIds.push(row[idKey]);
        }
      });
      noSelectIds.forEach(id => {
        if (selectAllIds.indexOf(id) >= 0) {
          for (let i = 0; i < that.multipleSelectionAll.length; i++) {
            if (that.multipleSelectionAll[i][idKey] == id) {
              // 如果总选择中有未被选中的，那么就删除这条
              that.multipleSelectionAll.splice(i, 1);
              break;
            }
          }
        }
      });
    }, 
    // // 得到选中的所有数据
    // getAllSelectionData() {
    //   // 再执行一次记忆勾选数据匹配，目的是为了在当前页操作勾选后直接获取选中数据
    //   this.changePageCoreRecordData();
    // },
    handleSelectionChange(val) {
      this.multipleSelection  = val;
      // debugger
      setTimeout(()=>{
        this.changePageCoreRecordData()
      },500)
    },
    // 确定
    determine() {
      if (this.totalAmount == this.cardAmount) {
        let shopCardList = [];
        for (let item of this.multipleSelectionAll) {
          shopCardList.push({cardId: item.id, cardDenomination: item.cardDenomination });
        }
        let ruleForm = {
          batchCode: this.batchCode,
          terminalSource:this.sourceCategory,
          shopCardList: shopCardList
        };
        this.axios.post(api.shopCardBinding, ruleForm).then(data => {
          let res = data.data;
          if (res.code === 200) {
            this.$message({
              type: "success",
              message: "操作成功"
            });
            this.$router.push({ 
              path: "./shoppingCardSettlementTobeConfirm",
              query: { 
                batchCode: this.batchCode,
                sourceCategory: this.sourceCategory 
              }
            });
          }
        });
      } else {
        this.$message({
          type: "warning",
          message: "选择的购物卡结佣金额须等于待结佣购物卡金额!"
        });
      }
    },
    // 返回
    goBack() {
      this.$router.go(-1)
    },
    // 经纪人信息和订单明细
    brokerInfo() {
      this.axios
        .post(api.getSettleCommDetail, { batchCode: this.batchCode,terminalSource:this.sourceCategory})
        .then(res => {
          if (res.data.code === 200) {
            this.brokerApply = res.data.data.brokerApply;
            this.totalAmount = res.data.data.brokerApply.totalAmount; // 订单金额合计
            this.awardInfoList = res.data.data.awardInfoList;
            this.tableConfig.devId = res.data.data.brokerApply.devId;
            this.cartList();
          }
        });
    },
    // 购物卡列表 （结佣和更改共用）
    cartList() {
      this.axios
        .post(api.getAllAvailableShopCardList, this.tableConfig)
        .then(res => {
          if (res.data.code === 200) {
            this.cartLists = res.data.data.list;
            this.cartTotal = res.data.data.total;
            setTimeout(() => {
              this.setSelectRow();
            }, 200);
          }
        });
    },
    // 确认结佣
    confirm() {
      if (this.cardAmount != this.totalAmount) {
        return this.$message({
          type: "error",
          message: "选择的购物卡结佣金额须等于待结佣购物卡金额!"
        });
      }
      let shopCardList = [];
      for (let item of this.multipleSelectionAll) {
        shopCardList.push({
          cardId: item.id,
          cardDenomination: item.cardDenomination
        });
      }
      let ruleForm = {
        batchCode: this.batchCode,
        terminalSource:this.sourceCategory,
        shopCardList: shopCardList
      };
      this.axios.post(api.settleConfirm, ruleForm).then(data => {
        let res = data.data;
        if (res.code === 200) {
          this.$message({
            type: "success",
            message: "操作成功"
          });
          this.$router.push({ path: "./shoppingCardSettlement" });
        }
      });
    },
    onClear() {
      this.$router.push("./shoppingCardSettlement");
    },
    handleSizeChange(size) {
      this.changePageCoreRecordData();
      this.tableConfig.pageSize = size;
      this.cartList();
    },
    handleCurrentChange(page) {
      this.changePageCoreRecordData();
      this.tableConfig.pageNum = page;
      this.cartList();
    }
  }
};
</script>
<style lang="stylus" scoped>
.commission {
  font-size: 14px;

  .order {
    margin-bottom: 25px;
  }

  .textTitle {
    line-height: 40px;
    margin-top: 20px;
  }

  .textSub {
    width: 100%;
    padding-left: 5px;
    box-sizing: border-box;
    background: #eceaea;
    line-height: 35px;
  }

  table {
    border-collapse: collapse;
    margin: 0 auto;
  }

  table tr td {
    border: 1px solid #ccc;
    line-height: 40px;
    text-align: center;
  }

  .forms {
    margin: 15px auto;
    text-align: center;
  }
}
</style>


